package com.zmx.common.common.utils.sdk;

import java.io.*;

/**
 * @Description: 深度拷贝
 * @ClassName: DeepClone
 * @Author zhaomxr
 * @Date 2021-12-03 15:33
 */
public class DeepClone {

    /**
     * 基于序列化实现深度拷贝，将jvm中数据利用输入输出流反序列化 返回复制后对象
     *
     * @return
     */
    public static <T extends Serializable> T deepClone(T t) {
        if(t == null){
            return null;
        }
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(t);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException("深度拷贝失败！", e);
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
